﻿using Grpc.Core;
using Grpc.Core.Interceptors;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace gRPCService
{
    public class ServiceLoggerInterceptor : Interceptor
    {
        private readonly ILogger<ServiceLoggerInterceptor> _logger;

        public ServiceLoggerInterceptor(ILogger<ServiceLoggerInterceptor> logger)
        {
            _logger = logger;
        }


        public override Task DuplexStreamingServerHandler<TRequest, TResponse>(IAsyncStreamReader<TRequest> requestStream, IServerStreamWriter<TResponse> responseStream, ServerCallContext context, DuplexStreamingServerMethod<TRequest, TResponse> continuation)
        {
            LogCall<TRequest, TResponse>(MethodType.Unary, context);

            return base.DuplexStreamingServerHandler(requestStream, responseStream, context, continuation);
        }


        private void LogCall<TRequest, TResponse>(MethodType methodType, ServerCallContext context)
        where TRequest : class
        where TResponse : class
        {
            _logger.LogWarning($"Starting call. Type: {methodType}. Request: {typeof(TRequest)}. Response: {typeof(TResponse)}");
        }

    }
}
